package com.huterox.second.controller;

import com.huterox.second.dao.message.LoginMessage;
import com.huterox.second.dao.pojo.User;
import com.huterox.second.server.UserService;
import com.huterox.second.utils.TokenProccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@ResponseBody
public class Login {

    @Autowired
    UserService userService;
    @Autowired
    LoginMessage loginMessage;

    @Autowired
    TokenProccessor tokenProccessor;

    @PostMapping(value = "/login" )
    public LoginMessage login(@RequestBody Map<String,Object> accountMap, HttpSession session){
        String account;
        String username;
        String password;
        User user = null;
        try {
            account = (String) accountMap.get("account");
            password = (String) accountMap.get("password");
            user = userService.selectUserByAccountAndPassword(account,password);
        }catch (Exception e){
            e.printStackTrace();
            loginMessage.setSuccess(-1);
        }

        if(user!= null){
//            这里我们把用户的id给前端，后面我们验证这个id就好了
            String token = tokenProccessor.createToken(String.valueOf(user.getId()));

            loginMessage.setSuccess(1);
            loginMessage.setToken(token);
        }else {
            loginMessage.setSuccess(-1);
        }

        return loginMessage;
    }
}
